package com.example.aiyou.passwordmanage.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.example.aiyou.passwordmanage.R;

public class PasswordActivity extends AppCompatActivity {
    private EditText passwordText;
    private EditText newPasswordText;
    private EditText rePasswordText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_password);
        passwordText = (EditText) findViewById(R.id.password);
        newPasswordText = (EditText) findViewById(R.id.new_password);
        rePasswordText = (EditText) findViewById(R.id.re_password);
        Button button = (Button) findViewById(R.id.button_save);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                attemptRePassword();
            }
        });
    }

    private void attemptRePassword() {
        SharedPreferences sharedPreferences = getSharedPreferences("data",MODE_PRIVATE);
        String p = sharedPreferences.getString("password","");
        String password = passwordText.getText().toString();
        String newPassword = newPasswordText.getText().toString();
        String rePassword = rePasswordText.getText().toString();
        boolean cancel = true;
        if(TextUtils.isEmpty(password)){
            passwordText.setError("请输入密码");
            passwordText.requestFocus();
            return;
        }
        if(TextUtils.isEmpty(newPassword)){
            newPasswordText.setError("请输入新密码");
            newPasswordText.requestFocus();
            return;
        }
        if(TextUtils.isEmpty(rePassword)){
            rePasswordText.setError("请再次输入密码");
            rePasswordText.requestFocus();
            return;
        }
        if(!password.equals(p)){
            passwordText.setError("密码错误");
            passwordText.requestFocus();
            return;
        }
        if(!rePassword.equals(newPassword)){
            rePasswordText.setError("两次密码不匹配");
            rePasswordText.requestFocus();
            return;
        }
        SharedPreferences.Editor editor = getSharedPreferences("data",MODE_PRIVATE).edit();
        editor.putString("password",rePassword);
        editor.apply();
        Intent i = new Intent(PasswordActivity.this,SettingsActivity.class);
        i.putExtra("meg","success");
        startActivity(i);
        finish();
    }

    public void actionStart(Context context){
        Intent intent = new Intent(context,PasswordActivity.class);
        context.startActivity(intent);
    }
}
